const express = require("express");
const multer = require("multer");
const path = require("path");
const history = require("connect-history-api-fallback");
const app = express();
const PORT = "3000";

// 跨域请求
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  if (req.method == "OPTIONS") res.sendStatus(200); // 让option请求快速结束
  else next();
});

// 解析json
app.use(express.json());

// 配对history模式

// 上传文件
const update = multer({
  // 指定文件上传的临时目录
  dest: "./public/upload/temp",
});
app.use(update.any());
// 静态文件预览目录

// 注册路由
app.use("/test", require("./routers/TestRouter"));
app.use("/", require("./routers/AdminRouter"));
app.use("/", require("./routers/CategoryRouter"));
app.use("/", require("./routers/BlogRouter"));
app.use("/", require("./routers/UploadRouter"));

app.get("/", (req, res) => {
  console.log("/");
  res.send("hello world");
});
// 先定义路由后使用这个中间件
app.use(history());
// 最后配置 静态资源文件
app.use(express.static(path.join(__dirname, "public")));

app.listen(PORT, () => {
  console.log(`${PORT}端口已启动`);
});
